
package com.putao.album.main.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 * ???ViewGroup
 */
public class FamilyUserCollectionItemView extends ViewGroup {
    private static final String TAG = "CustomViewGroup";
    int cellWidthSize = 0;
    int cellHeightSize = 0;

    // ===========================================================
    // Constructors
    // ===========================================================
    public FamilyUserCollectionItemView(Context context) {
        super(context);
    }

    public FamilyUserCollectionItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FamilyUserCollectionItemView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    int widthMode;
    int heightMode;

    // ===========================================================
    // Methods for/from SuperClass/Interfaces
    // ===========================================================
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int widthSize = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
        int heightSize = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
//        MeasureSpec.getMode(widthMeasureSpec);
        widthMode = MeasureSpec.getMode(widthMeasureSpec);
        heightMode = MeasureSpec.getMode(heightMeasureSpec);
        cellWidthSize = widthSize / 3;
        cellHeightSize = cellWidthSize;
        int heightMeasured = 0;
        if (heightMeasureSpec == 0) {
            int rowCount = (int) Math.ceil(getChildCount() / 3.0f);
            heightMeasured = rowCount * cellHeightSize;
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightMeasured, MeasureSpec.AT_MOST);
        }
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        int mTotalHeight = 0;
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            int measureHeight = childView.getMeasuredHeight();
            int measuredWidth = childView.getMeasuredWidth();
            int offset = (cellWidthSize - measuredWidth) / 2;
            childView.layout(left + offset, mTotalHeight, left + measuredWidth, mTotalHeight + measureHeight);
            if ((i + 1) % 3 == 0) {
                left = 0;
                mTotalHeight += measureHeight;
            } else {
                left += cellWidthSize;
            }
        }
    }
}
